﻿#region << 版 本 注 释 >>
/*----------------------------------------------------------------
// Copyright (C) 2021 kingerrobot
// 版权所有。 
//
// 文件名：BProdProduct
// 文件功能描述：
//
// 创建者：名字 (zzl)
// 时间：2021/12/7 16:18:01
//
// 修改人：
// 时间：
// 修改说明：
// 版本：V1.0.0
//----------------------------------------------------------------*/
#endregion
using System.Collections.Generic;

namespace KingerRobot.MexicoSailunWMS.SpiService;




internal class BProdProduct : IProdProduct
{

    private readonly static IProdSku _ProdSku = new BProdSku();
    private readonly static IProdMaterial _ProdMaterial = new BProdMaterial();
    private readonly static IRcsEquip _RcsEquip = new BRcsEquip();
    private readonly static IProdSkuProduct _ProdSkuProduct = new BProdSkuProduct();
    private readonly static IMesGreenTireBuilding _MesGreenTireBuilding = new BMesGreenTireBuilding();

    public POProdProduct CreateOrUpdateProduct(ProdProductBean prodProductBean)
    {
        var productCode = prodProductBean.ProductCode;
        var product = GetProductByCode(productCode);
        var MdEquipId = _RcsEquip.GetRcsEquipByCode(prodProductBean.MdEquipCode)?.Id ?? 0L;
        var gtStatus = prodProductBean.QuailtyStatus == 1 ? ConstFields.UnQualifiedProductStatus : ConstFields.QualifiedProductStatus;

        if (product is not null)
        {
            var productInfo = new POProdProduct()
            {
                ProductCode = prodProductBean.ProductCode,
                MdEquipId = MdEquipId,
                MaterialId = prodProductBean.MaterialId,
                MdTime = prodProductBean.MdTime,
                GtStatus = gtStatus,
                TireLock = prodProductBean.TireLock,
                ProductBatch = prodProductBean.ProductBatch,
                UpdateTime = DateTime.Now
            };
            UpdateProduct(productInfo);
            productInfo.Id = product.Id;
            return productInfo;
        }

        POProdProduct pProdProduct = new()
        {
            Id = XID.Nextval,
            ProductCode = prodProductBean.ProductCode,
            MdEquipId = MdEquipId,
            MaterialId = prodProductBean.MaterialId,
            ProductBatch = prodProductBean.ProductBatch,
            MdTime = prodProductBean.MdTime,
            GtStatus = gtStatus,
            TireLock = prodProductBean.TireLock,
        };
        var db = Db.Default;
        db.ProdProducts.Insert(pProdProduct);
        return pProdProduct;
    }
    public int UpdateProduct(POProdProduct product)
    {
        var db = Db.Default;
        var result = db.ProdProducts.Where(t => t.ProductCode == product.ProductCode).Update(product);
        return result;
    }

    public List<POProdProduct> GetOProdProducts()
    {
        var db = Db.Default;
        var result = db.ProdProducts.ToList();
        return result;
    }
    public POProdProduct CreateProduct(ProdProductBean prodProductBean)
    {
        var frozen = IsProductFrozen(prodProductBean.ProductCode);
        POProdProduct pProdProduct = new()
        {
            Id = XID.Nextval,
            ProductCode = prodProductBean.ProductCode,
            MdEquipId = prodProductBean.MdEquipId,
            MaterialId = prodProductBean.MaterialId,
            ProductBatch = prodProductBean.ProductBatch,
            GtStatus = prodProductBean.GtStatus,
            Frozen = frozen,
            MdTime = prodProductBean.MdTime,
        };
        var db = Db.Default;
        db.ProdProducts.Insert(pProdProduct);
        return pProdProduct;
    }
    private int IsProductFrozen(string barCode)
    {

        var db = Db.Default;

        var frozen = db.MesProductFrozens.Where(t => t.Barcode == barCode).FirstOrDefault();

        return "Y".Equals(frozen) ? 1 : 0;
    }
    public POProdProduct DeleteProduct(string productCode)
    {
        var db = Db.Default;
        var result = GetProductByCode(productCode);
        if (result != null)
        {
            db.ProdProducts.Remove(result);
            var num = db.SaveChanges();
            if (num == 0)
            {
                return null;
            }
            return result;
        }
        return result;
    }

    public List<POProdProduct> GetProductListByCode(string code)
    {
        var db = Db.Default;
        var result = db.ProdProducts.Where(t => t.ProductCode == code).ToList();
        return result;
    }
    public List<ProductInfo> GetProductListByCodeV1(string code, string orderByName, string orderByType)
    {
        List<ProductInfo> result = new();

        IQueryable<ProductInfo> data;

        var db = Db.Default;
        if (!String.IsNullOrWhiteSpace(code))
        {
            data = db.ProdProducts.Join(db.ProdMaterials, f => f.MaterialId, s => s.Id, (f, s) => new ProductInfo
            {
                code = f.ProductCode,
                materialCode = s.MaterialCode,
                materialName = s.MaterialName,
                //materialSpec = s.Spec,
                mdTime = f.MdTime,
            }).Where(t => t.code.Contains(code)).Take(1000);//.ToList();

            ////IQueryable<ProductInfo> p = result1;
            ////result = result1.OrderBy("mdTime").ToList();

        }
        else
        {
            data = db.ProdProducts.Join(db.ProdMaterials, f => f.MaterialId, s => s.Id, (f, s) => new ProductInfo
            {
                code = f.ProductCode,
                materialCode = s.MaterialCode,
                materialName = s.MaterialName,
                mdTime = f.MdTime,
            }).Take(1000);

        }
        if (!string.IsNullOrWhiteSpace(orderByName))
        {
            if (orderByType == "ASC")
            {

                result = data.OrderBy(orderByName).ToList();
            }
            else
            {
                result = data.OrderByDescending(orderByName).ToList();
            }
        }
        else
        {
            result = data.OrderByDescending(t => t.mdTime).ToList();
        }

        return result;
    }



    public ProdProductBindingBean CreateProductBindingInfo(ProductBindingInfoBean productBindingInfoBean)
    {
        // 记录胎胚信息
        var productCode = productBindingInfoBean.ProductCode;
        var productBatch = productBindingInfoBean.ProductBatch;

        //这个地方实际上是规格
        var materialCode = productBindingInfoBean.MaterialCode;
        var materialName = productBindingInfoBean.MaterialName;

        var mdTime = productBindingInfoBean.ProductTime ?? DateTime.Now;
        var MdEquipCode = productBindingInfoBean.ProductEquip;
        var tireLock = productBindingInfoBean.TireLock ?? 0;
        var qualityStatus = productBindingInfoBean.QualityStatus ?? 0;

        //此处添加的是mes系统的mesId 要与其他地方保持一致
        var mesId = _ProdMaterial.GetMaterialByCode(materialCode)?.MesId;
        var building = _MesGreenTireBuilding.CreateOrUpdateMesGreenTireBuilding(productCode, mesId, MdEquipCode, mdTime, tireLock, qualityStatus, productBatch);


        // 查找物料
        var material = _ProdMaterial.GetMaterialByCode(materialCode);
        if (material == null)
        {
            // 添加物料
            material = _ProdMaterial.CreateMaterial(materialCode, materialName);
        }


        // 删除所有与产品相关数据 lsq 可能出现一条胎多次入库所以不删除之前的SKU等信息
        //DeleteProductBindingInfo(productCode);
        //long mdEquipId = 0;
        //var mdEquip = _RcsEquip.GetRcsEquipByCode(mdEquipCode);
        //if (mdEquip != null)
        //{
        //    mdEquipId = mdEquip.Id.GetValueOrDefault();
        //}


        // 添加产品
        var prodProductBean = new ProdProductBean
        {
            ProductBatch = productBatch,
            ProductCode = productCode,
            MaterialId = material?.Id ?? 0,
            MdTime = mdTime,
            MdEquipCode = MdEquipCode,
            QuailtyStatus = qualityStatus,
            TireLock = tireLock,
        };
        var product = CreateOrUpdateProduct(prodProductBean);



        // 添加sku
        var skuCode = product?.ProductCode;
        var materialId = product?.MaterialId ?? 0;
        var sku = _ProdSku.CreateProdSku(new()
        {
            SkuCode = skuCode,
            MaterialId = materialId,
            ProductBatch = productBatch,
            MdTime = mdTime,
        });


        // 添加产品 和 sku 关联
        var skuId = sku?.Id ?? 0;
        var productId = product?.Id ?? 0;
        var skuProduct = _ProdSkuProduct.CreateProdSkuProduct(skuId, productId, materialId, mdTime);

        return new ProdProductBindingBean
        {
            POMesGreenTireBuilding = building,
            POProdMaterial = material,
            POProdProduct = product,
            POProdSku = sku,
            POProdSkuProduct = skuProduct,
        };
    }

    public ProdProductBindingBean GetProductBindingInfoByCode(string code)
    {
        var db = Db.Default;
        var result = db.ProdProducts
            .Where(t => t.ProductCode == code)
            .Join(db.ProdSkuProducts, f => f.Id, s => s.ProductId, (f, s) => new { Product = f, SkuProduct = s })
            .Join(db.ProdSkus, f => f.SkuProduct.SkuId, s => s.Id, (f, s) => new { f.Product, f.SkuProduct, Sku = s })
            .Join(db.ProdMaterials, f => f.Product.MaterialId, s => s.Id, (f, s) =>
            new ProdProductBindingBean
            {
                POProdProduct = f.Product,
                POProdSkuProduct = f.SkuProduct,
                POProdSku = f.Sku,
                POProdMaterial = s,
            }).OrderByDescending(t => t.POProdSku.CreateTime).FirstOrDefault();

        return result;
    }

    public List<ProdProductBindingBean> GetProductBindingInfoByCodes(List<string> codes)
    {
        var db = Db.Default;
        var result = db.ProdProducts
            .Where(t => codes.Contains(t.ProductCode))
            .Join(db.ProdSkuProducts, f => f.Id, s => s.ProductId, (f, s) => new { Product = f, SkuProduct = s })
            .Join(db.ProdSkus, f => f.SkuProduct.SkuId, s => s.Id, (f, s) => new { f.Product, f.SkuProduct, Sku = s })
            .Join(db.ProdMaterials, f => f.Product.MaterialId, s => s.Id, (f, s) =>
            new ProdProductBindingBean
            {
                POProdProduct = f.Product,
                POProdSkuProduct = f.SkuProduct,
                POProdSku = f.Sku,
                POProdMaterial = s,
            }).OrderByDescending(t => t.POProdSku.CreateTime).ToList();

        return result;
    }
    public ProdProductBindingBean GetProductBindingInfoBySkuId(long skuId)
    {
        var db = Db.Default;
        var result = db.ProdSkuProducts.Where(t => t.SkuId == skuId)
            .Join(db.ProdProducts, f => f.ProductId, s => s.Id, (f, s) => new { Product = s, SkuProduct = f })
            .Join(db.ProdSkus, f => f.SkuProduct.SkuId, s => s.Id, (f, s) => new { f.Product, f.SkuProduct, Sku = s })
            .Join(db.ProdMaterials, f => f.Product.MaterialId, s => s.Id, (f, s) =>
            new ProdProductBindingBean
            {
                POProdProduct = f.Product,
                POProdSkuProduct = f.SkuProduct,
                POProdSku = f.Sku,
                POProdMaterial = s,
            }).FirstOrDefault();

        return result;
    }

    public long GetSkuIdByCode(string code) => GetProductBindingInfoByCode(code)?.POProdSku?.Id ?? 0;

    public string GetCodeBySkuId(long skuId) => GetProductBindingInfoBySkuId(skuId)?.POProdProduct?.ProductCode;

    public POProdProduct GetProductByCode(string code)
    {
        var db = Db.Default;
        var result = db.ProdProducts.Where(t => t.ProductCode.Contains(code)).FirstOrDefault();
        return result;
    }

    public bool HasProductByCode(string code) => GetProductByCode(code) != null;



}
